package cn.wenhe9.novel.controller.author;

import cn.wenhe9.novel.auth.UserHolder;
import cn.wenhe9.novel.constant.ApiRouterConsts;
import cn.wenhe9.novel.constant.ResultCodeEnum;
import cn.wenhe9.novel.constant.SystemConfigConsts;
import cn.wenhe9.novel.domain.dto.*;
import cn.wenhe9.novel.domain.entity.author.AuthorIncome;
import cn.wenhe9.novel.domain.entity.author.AuthorIncomeDetail;
import cn.wenhe9.novel.domain.entity.author.AuthorInfo;
import cn.wenhe9.novel.domain.vo.AuthorRegisterVo;
import cn.wenhe9.novel.domain.vo.BookPublishVo;
import cn.wenhe9.novel.domain.vo.ChapterPublishVo;
import cn.wenhe9.novel.domain.vo.ChapterUpdateVo;
import cn.wenhe9.novel.exception.NovelException;
import cn.wenhe9.novel.result.PageResultDto;
import cn.wenhe9.novel.result.ResultResponse;
import cn.wenhe9.novel.service.AuthorService;
import cn.wenhe9.novel.service.BookService;
import cn.wenhe9.novel.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 作家模块相关接口 API
 * @author DuJinliang
 * 2022/6/1
 */
@Slf4j
@RestController
@Api(tags = "作家模块相关接口 API")
@RequestMapping(ApiRouterConsts.API_AUTHOR_URL_PREFIX)
public class AuthorController {

    @Resource
    private AuthorService authorService;

    @Resource
    private BookService bookService;

    @Resource
    private JwtUtils jwtUtils;

    /**
     * 校验笔名是否存在
     * */
    @ApiOperation("校验笔名是否存在")
    @GetMapping("checkPenName")
    public ResultResponse<Boolean> checkPenName(String penName){
        return ResultResponse.ok(authorService.checkPenName(penName));
    }

    /**
     * 作家注册接口
     */
    @ApiOperation("作家注册接口")
    @PostMapping("register")
    public ResultResponse<Void> register(@Valid @RequestBody AuthorRegisterVo vo, HttpServletRequest request) {
        String token = request.getHeader(SystemConfigConsts.HTTP_AUTH_HEADER_NAME);
        if (StringUtils.isEmpty(token)) {
            throw new NovelException(ResultCodeEnum.USER_LOGIN_EXPIRED);
        }
        Long userId = jwtUtils.parseToken(token, SystemConfigConsts.NOVEL_FRONT_KEY);
        authorService.register(userId, vo);
        return ResultResponse.ok();
    }


    /**
     * 作家发布小说分页列表查询
     * */
    @ApiOperation("作家发布小说分页列表查询")
    @GetMapping("book/list/{page}/{limit}")
    public ResultResponse<PageResultDto<BookInfoDto>> listBookByPage(
            @PathVariable(name = "page") @DefaultValue("1") Long page,
            @PathVariable(name = "limit") @DefaultValue("5") Long limit
    ){
        return ResultResponse.ok(bookService.listBookPageByAuthorId(UserHolder.getAuthorId(), page, limit));
    }

    /**
     * 发布小说
     * */
    @PostMapping("book")
    public ResultResponse<Void> addBook(@RequestBody BookPublishVo vo){

        AuthorInfo authorInfo = checkAuthor();

        vo.setBookDesc(vo.getBookDesc()
                .replaceAll("\\n","<br>")
                .replaceAll("\\s","&nbsp;"));
        //发布小说
        bookService.publishBook(vo, authorInfo.getId(), authorInfo.getPenName());

        return ResultResponse.ok();
    }

    /**
     * 根据小说id分页查询章节信息
     */
    @GetMapping("book/chapter/list/{page}/{limit}/{bookId}")
    public ResultResponse<PageResultDto<BookChapterDto>> listChapterByBookId(
            @PathVariable(name = "page") Long page,
            @PathVariable(name = "limit") Long limit,
            @PathVariable(name = "bookId") Long bookId
    ){
        return ResultResponse.ok(bookService.listChaptersByPage(page, limit, bookId));
    }


    /**
     * 删除章节
     */
    @DeleteMapping("book/chapter/{chapterId}")
    public ResultResponse<Void> deleteIndex(@PathVariable("chapterId") Long chapterId) {

        checkAuthor();

        //删除章节
        bookService.deleteChapter(chapterId, UserHolder.getAuthorId());

        return ResultResponse.ok();
    }


    /**
     * 发布章节内容
     */
    @PostMapping("book/chapter")
    public ResultResponse<Void> addBookContent(@RequestBody ChapterPublishVo vo) {
        checkAuthor();

        vo.setChapterContent(
                vo.getChapterContent().replaceAll("\\n", "<br>")
                .replaceAll("\\s", "&nbsp;")
        );
        //发布章节内容
        bookService.publishChapter(vo, UserHolder.getAuthorId());

        return ResultResponse.ok();
    }

    /**
     * 查询章节信息
     */
    @GetMapping("/book/chapter/{chapterId}")
    public ResultResponse<BookChapterUpdateDto> queryChapterContent(
            @PathVariable(name = "chapterId") Long chapterId
    ) {

        checkAuthor();

        BookChapterUpdateDto bookChapterDto = bookService.getChapterInfoById(chapterId);

        bookChapterDto.setChapterContent(
                bookChapterDto.getChapterContent()
                        .replaceAll("<br>", "\n")
                        .replaceAll("&nbsp;", " "));

        return ResultResponse.ok(bookChapterDto);
    }

    /**
     * 更新章节内容
     */
    @PutMapping("book/chapter")
    public ResultResponse<Void> updateBookContent(@RequestBody ChapterUpdateVo vo) {
        checkAuthor();
        vo.setChapterContent(
                vo.getChapterContent().replaceAll("\\n", "<br>")
                .replaceAll("\\s", "&nbsp;"));
        //更新章节内容
        bookService.updateBookContent(vo, UserHolder.getAuthorId());

        return ResultResponse.ok();
    }


    /**
     * 作家日收入统计数据分页列表查询
     */
    @GetMapping("income/daily/list/{page}/{limit}")
    public ResultResponse<PageResultDto<AuthorIncomeDetailDto>> listIncomeDailyByPage(
            @PathVariable(name = "page") Long page,
            @PathVariable(name = "limit") Long pageSize
    ) {
        return ResultResponse.ok(authorService.listIncomeDailyByPage(page, pageSize, UserHolder.getAuthorId()));
    }


    /**
     * 作家月收入统计数据分页列表查询
     */
    @GetMapping("income/month/list/{page}/{limit}")
    public ResultResponse<PageResultDto<AuthorIncomeDto>> listIncomeMonthByPage(
            @PathVariable(name = "page") Long page,
            @PathVariable(name = "limit") Long pageSize
    ) {
        return ResultResponse.ok(authorService.listIncomeMonthByPage(page, pageSize, UserHolder.getAuthorId()));
    }

    private AuthorInfo checkAuthor() {
        //查询作家信息
        AuthorInfo authorInfo = authorService.queryAuthorById(UserHolder.getAuthorId());

        //判断作者状态是否正常
        if (authorInfo.getStatus() == 1) {
            //封禁状态，不能发布小说
            throw new NovelException(ResultCodeEnum.AUTHOR_STATUS_FORBIDDEN);
        }

        return authorInfo;
    }




}
